import { instance as request } from '../request'
import { EventSourcePolyfill } from 'event-source-polyfill'

/**
 * 给特定用户发消息
 * @param targetId
 * @param userId
 * @param message
 * @returns
 */
export const pushToTargetApi = (
  targetId: string,
  message: string
): PromiseRes =>
  request.post(`/websocket/push`, null, {
    params: { targetId: targetId, message: message },
  })

/**
 * 推送公告消息
 * @param message
 * @returns
 */
export const pushPublicMessageApi = (message: string): PromiseRes =>
  request.post(`/websocket/push/public`, message)

/**
 * 连接持久SSE服务
 * @param userId 用户id
 * @returns
 */
export const sseConnectEnduringApi = (): EventSource =>
  new EventSourcePolyfill(`/api1/sse/enduring/connect`, {
    headers: {
      Authorization: window.localStorage.getItem('token'),
      Connection: 'keep-alive',
      'Content-Type': 'text/event-stream;charset=UTF-8',
      'Cache-Control': 'no-cache',
    },
    heartbeatTimeout: 600000,
    withCredentials: false,
  })

/**
 * 连接聊天SSE服务
 * @param userId 用户id
 * @returns
 */
export const sseConnectChattingApi = (): EventSource =>
  new EventSourcePolyfill(`/api1/sse/chatting/connect`, {
    headers: {
      Authorization: window.localStorage.getItem('token'),
      Connection: 'keep-alive',
      'Content-Type': 'text/event-stream;charset=UTF-8',
      'Cache-Control': 'no-cache',
    },
    withCredentials: false,
  })

/**
 * 获取未读消息数量
 * @returns
 */
export const getNotReadMessageCountApi = (): PromiseRes =>
  request.get('/sse/notRead/count')

/**
 * 使用sse连接给特定用户发消息
 * @param receiverId 接收者id
 * @param message  发送的消息
 * @returns
 */
export const sseSendChattingMessageApi = (
  receiverId: string,
  message: string
): PromiseRes => request.post(`/sse/chatting/send/${receiverId}`, { message })

/**
 * 检查  发送未接收到的消息，存在则发送消息
 * @returns
 */
export const sseCheckChattingNotReceiveMessageApi = (): PromiseRes =>
  request.get('/sse/chatting/notReceive')
